//
//  AppDelegate.m
//  svqj
//
//  Created by xftt on 14-6-19.
//
//

#import "AppDelegate.h"
#import "MainViewController.h"
#import "XLConnection.h"
#import "XLResponse.h"

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [WeiboSDK registerApp:WB_APPKEY];
        [WXApi registerApp:WX_AppID];
    });
    if ([self isFirstLoad]) {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"设置"
                                                        message:@"请输入产品注册码!"
                                                       delegate:nil
                                              cancelButtonTitle:@"设置"
                                              otherButtonTitles:nil];
        alert.alertViewStyle = UIAlertViewStylePlainTextInput;
        alert.tag = 2;
        alert.delegate = self;
        [alert show];
    }
    else
    {
        XLConnection *connection = [[XLConnection alloc] initWithCompletionBlock:^(XLConnection *connection, XLResponse *response, NSError *error) {
            if (response) {
                NSArray *configData = [response result];
                NSString *version = [configData valueForKey:@"version"];
                NSString *str = [configData valueForKey:@"releaseNotes"];
                _downLink = [configData valueForKey:@"downLink"];
                if (![version isEqualToString:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"]]) {
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"发现新版本" message:str delegate:self cancelButtonTitle:@"立即更新" otherButtonTitles:nil];
                    alert.tag = 1;
                    [alert show];
                }
            }
        }];
        [connection checkUpdate];
    }
    [NSThread sleepForTimeInterval:1];
    UINavigationController *nav = [[UINavigationController alloc] init];
    MainViewController *root = [[MainViewController alloc] initWithNibName:nil bundle:nil];
    [nav setNavigationBarHidden:YES];
    [nav pushViewController:root animated:NO];
    self.window.rootViewController = nav;
    [self.window makeKeyAndVisible];
    return YES;
}

- (BOOL) isFirstLoad
{
    NSString* docPath = [NSHomeDirectory() stringByAppendingPathComponent: @"Documents"];
    NSString* imagePath = [NSString stringWithFormat: @"%@/logo.png", docPath];
    return ![[NSFileManager defaultManager] fileExistsAtPath:imagePath];
}

- (void)firstLoad
{
    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"设置"
                                                    message:@"请输入产品注册码!"
                                                   delegate:nil
                                          cancelButtonTitle:@"取消"
                                          otherButtonTitles:@"设置",nil];
    alert.alertViewStyle = UIAlertViewStylePlainTextInput;
    alert.tag = 3;
    alert.delegate = self;
    [alert show];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 2 || (alertView.tag == 3 && buttonIndex == 1)) {
        UITextField *txtSort = [alertView textFieldAtIndex:0];
        if ([txtSort.text length] > 0) {
            XLConnection *connection = [[XLConnection alloc] initWithCompletionBlock:^(XLConnection *connection, XLResponse *response, NSError *error) {
                if (response) {
                    if ([response isSuccessReturn]){
                    NSArray *settingData = [response result];
                    NSString *logoImgUrl = [settingData valueForKey:@"logo"];
                    NSString *titleApp = [settingData valueForKey:@"title"];
                    NSString* docPath = [NSHomeDirectory() stringByAppendingPathComponent: @"Documents"];
                    NSString* imagePath = [NSString stringWithFormat: @"%@/logo.png", docPath];
                    [[NSFileManager defaultManager] createFileAtPath:imagePath contents:[NSData dataWithContentsOfURL:[NSURL URLWithString:logoImgUrl]] attributes:nil];
                    NSArray *menuList = [settingData valueForKey:@"menu"];
                    NSUserDefaults *_Data = [NSUserDefaults standardUserDefaults];
                    [_Data setObject:menuList forKey:@"menuList"];
                    [_Data setObject:titleApp forKey:@"titleApp"];
                    [_Data synchronize];
                    UINavigationController *nav = [[UINavigationController alloc] init];
                    MainViewController *root = [[MainViewController alloc] initWithNibName:nil bundle:nil];
                    [nav setNavigationBarHidden:YES];
                    [nav pushViewController:root animated:NO];
                    self.window.rootViewController = nav;
                    [self.window makeKeyAndVisible];
                    }else{
                    if (alertView.tag == 3) {
                    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"设置"
                                                                    message:[response message]
                                                                   delegate:nil
                                                          cancelButtonTitle:@"取消"
                                                          otherButtonTitles:@"设置",nil];
                    alert.alertViewStyle = UIAlertViewStylePlainTextInput;
                    alert.tag = 3;
                    alert.delegate = self;
                    [alert show];
                    }else{
                        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"设置"
                                                                        message:[response message]
                                                                       delegate:nil
                                                              cancelButtonTitle:@"设置"
                                                              otherButtonTitles:nil];
                        alert.alertViewStyle = UIAlertViewStylePlainTextInput;
                        alert.tag = 2;
                        alert.delegate = self;
                        [alert show];
                    }
                }
                } else{
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络请求" message:@"请求失败" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                    [alert show];
                }
            }];
            [connection setNeedIndicator:YES];
            [connection setInfoWithCode:txtSort.text];
        }
        else
        {
            if (alertView.tag == 3) {
                UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"设置"
                                                                message:@"请输入产品注册码!"
                                                               delegate:nil
                                                      cancelButtonTitle:@"取消"
                                                      otherButtonTitles:@"设置",nil];
                alert.alertViewStyle = UIAlertViewStylePlainTextInput;
                alert.tag = 3;
                alert.delegate = self;
                [alert show];
            }else{
                UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"设置"
                                                                message:@"请输入产品注册码!"
                                                               delegate:nil
                                                      cancelButtonTitle:@"设置"
                                                      otherButtonTitles:nil];
                alert.alertViewStyle = UIAlertViewStylePlainTextInput;
                alert.tag = 2;
                alert.delegate = self;
                [alert show];
            }
        }
    }
    else if(alertView.tag == 1)
    {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:_downLink]];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"APP过期" message:@"当前版本已过期，请更新!" delegate:self cancelButtonTitle:@"更新" otherButtonTitles:nil];
        alert.tag = 1;
        [alert show];
    }
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    if (![WeiboSDK handleOpenURL:url delegate:self])
    {
        return [WXApi handleOpenURL:url delegate:self];
    }
    return YES;
}


#pragma mark - 3RD delegate

- (void)didReceiveWeiboRequest:(WBBaseRequest *)request
{
    
}

- (void)didReceiveWeiboResponse:(WBBaseResponse *)response
{
    
}


- (void)onReq:(BaseReq*)req
{
    
}

- (void)onResp:(BaseResp*)resp
{
    
}
@end
